<template>
  <div class="app-container">
    <div class="head-contain">
      <el-button type="primary" size="mini" class="file-btn" @click="openDialog"
        >设置文件索引</el-button
      >
      <h4 class="list-title operate-title">
        日志升级平台设备信息
        <el-button
          type="primary"
          size="mini"
          class="add_btn set_btn"
          @click="isSets"
          >设置运营商<i class="el-icon-plus el-icon--right"></i
        ></el-button>
        <el-button type="primary" size="mini" class="add_btn" @click="isAddTag"
          >设置标签<i class="el-icon-plus el-icon--right"></i
        ></el-button>
      </h4>
    </div>
    <el-row>
      <el-col :span="11" class="left-width">
        <el-table
          :data="listData"
          border
          ref="eomsTable"
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{
            padding: '2.5px 0',
            background: '#ECF1F7',
            textAlign: 'center',
          }"
          @selection-change="handleEomsSelect"
        >
          <el-table-column
            type="selection"
            width="40"
            fixed="left"
            :selectable="selectEomsEnable"
          >
          </el-table-column>
          <el-table-column
            width="200"
            :prop="columnProps[columnForm.code - 1]"
            label="设备编码"
          ></el-table-column>
          <el-table-column
            :prop="columnProps[columnForm.operate - 1]"
            label="运营商"
          >
            <template slot-scope="scope">
              <el-tooltip
                :content="scope.row[columnProps[columnForm.operate - 1]]"
                placement="top"
              >
                <span class="address">{{
                  scope.row[columnProps[columnForm.operate - 1]]
                }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            width="100"
            :prop="columnProps[columnForm.lng - 1]"
            label="经度"
          >
            <template slot-scope="scope">
              <el-tooltip
                :content="String(scope.row[columnProps[columnForm.lng - 1]])"
                placement="top"
              >
                <span class="address">{{
                  scope.row[columnProps[columnForm.lng - 1]]
                }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            width="100"
            :prop="columnProps[columnForm.lat - 1]"
            label="纬度"
          >
            <template slot-scope="scope">
              <el-tooltip
                :content="String(scope.row[columnProps[columnForm.lat - 1]])"
                placement="top"
              >
                <span class="address">{{
                  scope.row[columnProps[columnForm.lat - 1]]
                }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column
            label="地址"
            width="180"
            :prop="columnProps[columnForm.address - 1]"
          >
            <template slot-scope="scope">
              <el-tooltip
                :content="scope.row[columnProps[columnForm.address - 1]]"
                placement="top"
              >
                <span class="address">{{
                  scope.row[columnProps[columnForm.address - 1]]
                }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="total > 0"
          :total="total"
          :pageSizes="[15, 30, 45, 50, 200]"
          :page.sync="searchForm.page"
          :limit.sync="searchForm.limit"
          @pagination="pageChange"
        />
      </el-col>
      <el-col :span="2" class="imports">
        <el-tooltip content="同步" placement="top" v-if="listData.length > 0">
          <el-button size="small" class="import_btn" @click="isImport(1)"
            >> ></el-button
          >
        </el-tooltip>
        <br />
        <el-tooltip
          content="同步所有"
          placement="top"
          v-if="listData.length > 0"
        >
          <el-button size="small" class="import_btn" @click="isImport(2)"
            >>>></el-button
          >
        </el-tooltip>
      </el-col>

      <el-col :span="11" class="left-width">
        <el-table
          border
          :header-cell-style="{
            padding: '2.5px 0',
            background: '#ECF1F7',
            textAlign: 'center',
          }"
          width="100%"
          ref="multipleTable"
          :data="energyData"
          :cell-style="{ textAlign: 'center' }"
          v-loading="energyLoading"
          @selection-change="handleSelect"
        >
          <el-table-column
            type="selection"
            width="40"
            fixed="left"
            :selectable="selectEnable"
          >
          </el-table-column>
          <el-table-column
            label="设备编码"
            width="200"
            prop="code"
          ></el-table-column>
          <el-table-column prop="operatorName" label="运营商">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.operatorName" placement="top">
                <span class="address">{{ scope.row.operatorName }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column width="100" prop="lng" label="经度">
            <template slot-scope="scope">
              <el-tooltip :content="String(scope.row.lng)" placement="top">
                <span class="address">{{ scope.row.lng }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column width="100" prop="lat" label="纬度">
            <template slot-scope="scope">
              <el-tooltip :content="String(scope.row.lat)" placement="top">
                <span class="address">{{ scope.row.lat }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="地址" width="180" prop="address">
            <template slot-scope="scope">
              <el-tooltip :content="scope.row.address" placement="top">
                <span class="address">{{ scope.row.address }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 选择列索引弹框 -->
    <Dialog
      :visible="inxVisible"
      width="30%"
      :loading="dialogInxLoading"
      title="选择列索引"
      @confirmDialog="isSubmitDialog('columnForm')"
      @cancelDialog="cancelInxDialog"
    >
      <el-form
        ref="columnForm"
        :model="columnForm"
        label-width="130px"
        :rules="columnRules"
      >
        <el-form-item label="导入excel文件：">
          <el-upload
            action
            accept=".xlsx, .xls"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="onChange"
          >
            <el-button type="primary" size="mini" class="file-btn"
              >打开excel文件</el-button
            ><span v-if="tableData.length > 0">（已选择文件）</span>
          </el-upload>
        </el-form-item>

        <el-form-item label="设备编码：" prop="code">
          <el-input-number
            size="medium"
            v-model="columnForm.code"
            controls-position="right"
            :min="1"
            placeholder="请输入设备编码索引"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="运营商：">
          <el-input-number
            size="medium"
            v-model="columnForm.operate"
            controls-position="right"
            :min="1"
            placeholder="请输入运营商索引"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="经度：">
          <el-input-number
            size="medium"
            v-model="columnForm.lng"
            controls-position="right"
            :min="1"
            placeholder="请输入经度索引"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="纬度：">
          <el-input-number
            size="medium"
            v-model="columnForm.lat"
            controls-position="right"
            :min="1"
            placeholder="请输入纬度索引"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="地址：">
          <el-input-number
            size="medium"
            v-model="columnForm.address"
            controls-position="right"
            :min="1"
            placeholder="请输入地址索引"
          ></el-input-number>
        </el-form-item>
      </el-form>
    </Dialog>

    <!-- 绑定运营商 -->
    <Dialog
      class="bind-operate"
      :visible="operateVisible"
      width="25%"
      :loading="dialogOperateLoading"
      title="设置运营商"
      @confirmDialog="isChooseOperate"
      @cancelDialog="cancelChooseDialog"
    >
      <h3 class="list-title bind-title">绑定运营商（可输入）</h3>
      <el-form ref="operateForm" class="operateForm">
        <el-radio
          class="radio-one"
          label="1"
          v-model="isOperateRadio"
          @click.native.prevent="radioClick()"
          ><el-form-item label="运营商">
            <el-input
              width="100%"
              v-model="operateInput"
              placeholder="请输入运营商"
            ></el-input> </el-form-item
        ></el-radio>
      </el-form>
    </Dialog>

    <!-- 新增设备标签 -->
    <Dialog
      :visible="visible"
      width="26%"
      :loading="dialogBtnLoading"
      title="新增设备标签"
      @confirmDialog="submitDialogForm('dialogForm')"
      @cancelDialog="cancelDialog"
    >
      <el-form
        ref="dialogForm"
        :model="dialogForm"
        label-width="70px"
        :rules="dialogRules"
      >
        <el-form-item label="已选设备">
          <div class="tags-data">
            <span
              v-for="(item, index) in selectData"
              :key="index"
              class="tag-one"
            >
              <el-tag v-if="index < 4">{{ item.code }}</el-tag></span
            >
          </div>
          <div class="more" v-if="selectData.length > 4">
            ......等{{ selectData.length }}个设备
          </div>
        </el-form-item>
        <el-form-item label="标签" prop="tagsId">
          <el-radio-group v-model="dialogForm.tagsId">
            <el-radio
              class="tag-radio"
              :label="item.id"
              v-for="(item, index) in tagList"
              :key="index"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
          <el-button
            type="primary"
            size="mini"
            plain
            @click="tagVisible = true"
            class="add_tag_btn"
            icon="el-icon-plus"
          ></el-button>
        </el-form-item>
        <el-form
          v-show="tagVisible"
          class="tagForm"
          :inline="true"
          ref="tagForm"
          :model="tagForm"
          label-width="120px"
          :rules="tagRules"
          ><el-form-item prop="name">
            <el-input
              v-model="tagForm.name"
              placeholder="请输入标签名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            ><el-button type="primary" size="small" plain @click="isSubmitTag"
              >确定</el-button
            ><i class="el-icon-close" @click="tagVisible = false"></i
          ></el-form-item>
        </el-form>
      </el-form>
    </Dialog>

    <Dialog
      :visible="setOperateVisible"
      width="18%"
      :loading="setOperateLoading"
      title="设置运营商"
      class="operateDialog"
      @confirmDialog="isSetOperate"
      @cancelDialog="cancelSetDialog"
    >
      <div>
        <el-input
          v-model="setOperateName"
          placeholder="请输入运营商"
        ></el-input>
      </div>
    </Dialog>
  </div>
</template>

<script>
import * as xlsx from "xlsx/xlsx.mjs";
import { handleConfirm } from "@/utils/messageBox";

import { datasync } from "@/api/system";

import Table from "@/components/Table";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Dialog from "@/components/Dialog";

export default {
  name: "App",
  components: { Pagination, Table, Dialog },

  data() {
    return {
      listLoading: false,
      total: 0,
      tableData: [],
      listData: [],
      searchForm: {
        page: 1,
        limit: 15,
      },

      inxVisible: false,
      dialogInxLoading: false,
      columnForm: {
        code: "13",
        operate: undefined,
        lng: "21",
        lat: "22",
        address: "16",
      },
      columnRules: {
        code: [
          { required: true, message: "请输入设备编码索引", trigger: "blur" },
        ],
      },
      columnProps: [],
      selectEomsData: [],
      // 绑定运营商弹框
      operateVisible: false,
      dialogOperateLoading: false,
      energyData: [],
      energyLoading: false,
      operateInput: "",
      isOperateRadio: "",
      selectData: [], //选中data

      visible: false,
      dialogBtnLoading: false,
      dialogForm: {
        codes: "",
        tagsId: "",
      },
      dialogRules: {
        tagsId: [{ required: true, message: "请选择标签", trigger: "change" }],
      },
      tagList: [],
      tagForm: {
        name: "",
      },
      tagRules: {
        name: [{ required: true, message: "请输入标签名称", trigger: "blur" }],
      },
      tagVisible: false,
      syncType: null, //同步类型：1.同步 2.同步所有

      // 设置运营商
      setOperateVisible: false,
      setOperateName: "",
      setOperateLoading: false,
    };
  },
  methods: {
    async onChange(file) {
      /**
       * 1. 使用原生api去读取好的文件
       * */
      // console.log("原始上传的文件", file);
      // 读取文件不是立马能够读取到的，所以是异步的，使用Promise
      let dataBinary = await new Promise((resolve) => {
        // Web API构造函数FileReader，可实例化对象，去调用其身上方法，去读取解析文件信息
        let reader = new FileReader(); // https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
        // console.log("实例化对象有各种方法", reader);
        reader.readAsBinaryString(file.raw); // 读取raw的File文件
        reader.onload = (ev) => {
          // console.log("文件解析流程进度事件", ev);
          resolve(ev.target.result); // 将解析好的结果扔出去，以供使用
        };
      });
      // console.log("读取出的流文件", dataBinary);

      /**
       * 2. 使用xlsx插件去解析已经读取好的二进制excel流文件
       * */
      let workBook = xlsx.read(dataBinary, { type: "binary", cellDates: true });
      // excel中有很多的sheet，这里取了第一个sheet：workBook.SheetNames[0]
      let firstWorkSheet = workBook.Sheets[workBook.SheetNames[0]];
      // 分为第一行的数据，和第一行下方的数据
      const header = this.getHeaderRow(firstWorkSheet);
      // console.log("读取的excel表头数据（第一行）", header);
      this.columnProps = header;
      const data = xlsx.utils.sheet_to_json(firstWorkSheet);
      // console.log("读取所有excel数据", data);
      this.tableData = data;
    },
    getHeaderRow(sheet) {
      const headers = []; // 定义数组，用于存放解析好的数据
      const range = xlsx.utils.decode_range(sheet["!ref"]); // 读取sheet的单元格数据
      let C;
      const R = range.s.r;
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[xlsx.utils.encode_cell({ c: C, r: R })];
        /* find the cell in the first row */
        let hdr = "UNKNOWN " + C; // <-- replace with your desired default
        if (cell && cell.t) hdr = xlsx.utils.format_cell(cell);
        headers.push(hdr);
      }
      return headers; // 经过上方一波操作遍历，得到最终的第一行头数据
    },
    // 分页
    pageChange(e) {
      this.searchForm = { ...e };
      this.listData = this.tableData.slice(
        e.limit * (e.page - 1),
        e.limit * e.page
      );
      this.getEnergyList();
    },
    isSubmitDialog(formName) {
      if (this.tableData.length == 0) {
        this.$message.error("请选择本地excel文件");
        return;
      }
      if (
        !this.columnForm.operate &&
        !this.columnForm.lng &&
        !this.columnForm.lat &&
        !this.columnForm.address
      ) {
        this.$message.error("运营商、经度、纬度、地址索引至少设置一个");
        return;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          handleConfirm(`确定要根据索引值显示数据吗？`, "warning", "提示")
            .then((res) => {
              this.listData = this.tableData.slice(0, 15);
              this.total = this.tableData.length;
              this.cancelInxDialog();
              this.getEnergyList();
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },
    cancelInxDialog() {
      this.inxVisible = false;
      this.dialogInxLoading = false;
    },
    clearData() {
      this.total = 0;
      this.tableData = [];
      this.listData = [];
      this.energyData = [];
      this.searchForm = {
        page: 1,
        limit: 15,
      };
      this.columnForm = {
        code: "13",
        operate: undefined,
        lng: "21",
        lat: "22",
        address: "16",
      };
    },
    selectEomsEnable(row, index) {
      if (row[this.columnProps[this.columnForm.code - 1]]) {
        return true;
      } else {
        return false;
      }
    },
    selectEnable(row, index) {
      if (row.code) {
        return true;
      } else {
        return false;
      }
    },
    openDialog() {
      this.inxVisible = true;
      this.clearData();
    },
    isImport(type) {
      this.syncType = type;
      // type 1:同步;2:同步所有;
      if (type == 1 && this.tableData.length == 0) {
        this.$message.error("暂无设备！");
        return;
      }
      if (type == 1 && this.selectEomsData.length == 0) {
        this.$message.error("请选择左侧需要同步的设备！");
        return;
      }
      this.operateVisible = true;
    },
    handleSelect(row, index) {
      this.selectData = row.filter((item) => item.code);
    },
    handleEomsSelect(row) {
      this.selectEomsData = row.filter(
        (item) => item[this.columnProps[this.columnForm.code - 1]]
      );
    },
    cancelChooseDialog() {
      this.operateVisible = false;
      this.operateInput = "";
      this.isOperateRadio = "";
    },
    isChooseOperate() {
      handleConfirm(
        `确定要同步${this.syncType == 2 ? "所有数据" : ""}并设置运营商吗？`,
        "warning",
        "提示"
      )
        .then((res) => {
          this.doChooseOperate();
        })
        .catch((err) => {});
    },
    doChooseOperate() {
      let params =
        this.syncType == 1
          ? JSON.parse(JSON.stringify(this.selectEomsData))
          : JSON.parse(JSON.stringify(this.tableData));
      // 返回code、address、lat、lng、operatorName
      let selectData = params.map((m) => {
        if (m[this.columnProps[this.columnForm.code - 1]]) {
          return {
            code: m[this.columnProps[this.columnForm.code - 1]],
            operatorName: m[this.columnProps[this.columnForm.operate - 1]],
            address: m[this.columnProps[this.columnForm.address - 1]],
            lat: m[this.columnProps[this.columnForm.lat - 1]],
            lng: m[this.columnProps[this.columnForm.lng - 1]],
          };
        }
      });
      if (selectData.length == 0) {
        this.$message.error("暂无设备信息，请重新选择！");
        return;
      }
      // 将输入框中运营商赋进每一项
      if (this.isOperateRadio) {
        for (let i = 0; i < selectData.length; i++) {
          selectData[i].operatorName = this.operateInput;
        }
      }
      this.dialogOperateLoading = true;
      datasync("/save", "post", selectData)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.cancelChooseDialog();
            this.selectEomsData = [];
            this.getEnergyList();
            this.$refs.eomsTable.clearSelection();
          }
        })
        .finally(() => (this.dialogOperateLoading = false));
    },
    getEnergyList() {
      this.energyLoading = true;
      this.energyData = [];
      let codes = this.listData.map((item) => {
        return item[this.columnProps[this.columnForm.code - 1]];
      });
      datasync("/energy/list", "post", codes)
        .then((res) => {
          let datas = res.data;
          let cloneArr1 = JSON.parse(JSON.stringify(this.listData));
          cloneArr1.forEach((m) => {
            let inx = datas.findIndex(
              (item) =>
                item.code == m[this.columnProps[this.columnForm.code - 1]]
            );
            if (inx != -1) {
              this.energyData.push(datas[inx]);
            } else {
              this.energyData.push({
                code: null,
                name: null,
                lng: null,
                lat: null,
                operatorName: null,
                address: null,
              });
            }
          });
        })
        .finally(() => {
          this.energyLoading = false;
        });
    },
    isAddTag() {
      if (this.energyData.length == 0) {
        this.$message.error("暂无设备！");
        return;
      }
      if (this.selectData.length == 0) {
        this.$message.error("请先选择设备！");
        return;
      }
      this.visible = true;
      this.getTagList();
    },
    // 查询全部标签
    async getTagList() {
      const data = await datasync("/tags/all");
      this.tagList = data.data;
    },
    submitDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          handleConfirm(`确定要给所选设备新增标签吗？`, "warning", "提示")
            .then((res) => {
              this.doAddTag();
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },
    doAddTag() {
      this.dialogBtnLoading = true;
      datasync(
        "/energy/insert/tags",
        "post",
        {
          codes: this.selectData
            .map((item) => {
              return item.code;
            })
            .join(","),
          tagsId: this.dialogForm.tagsId,
        },
        1
      )
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.cancelDialog();
            this.selectData = [];
            this.$refs.multipleTable.clearSelection();
          }
        })
        .finally(() => (this.dialogBtnLoading = false));
    },
    isSets() {
      if (this.energyData.length == 0) {
        this.$message.error("暂无设备！");
        return;
      }
      if (this.selectData.length == 0) {
        this.$message.error("请先选择设备！");
        return;
      }
      this.setOperateVisible = true;
    },
    cancelDialog() {
      this.visible = false;
      this.dialogForm = {
        codes: "",
        tagsId: "",
      };
      this.tagForm = {
        name: "",
      };
      this.dialogBtnLoading = false;
    },
    isSubmitTag() {
      this.$refs["tagForm"].validate((valid) => {
        if (valid) {
          handleConfirm(`确定要新增标签吗？`, "warning", "提示")
            .then((res) => {
              datasync(
                "/tags/insert",
                "post",
                { name: this.tagForm.name },
                1
              ).then((res) => {
                if (res.code == 200) {
                  this.$message.success(res.message);
                  this.tagVisible = false;
                  this.getTagList();
                }
              });
            })
            .catch((err) => {});
        } else {
          return false;
        }
      });
    },
    isSetOperate() {
      handleConfirm(`确认是否更改选中设备的运营商？`, "warning", "提示")
        .then((res) => {
          this.doSetOperate();
        })
        .catch((err) => {});
    },
    doSetOperate() {
      datasync("/update/operate", "post", {
        codes: this.selectData.map((item) => {
          return item.code;
        }),
        operateName: this.setOperateName,
      }).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.getEnergyList();
          this.cancelSetDialog();
          this.selectData = [];
          this.$refs.multipleTable.clearSelection();
        }
      });
    },
    cancelSetDialog() {
      this.setOperateVisible = false;
      this.setOperateName = "";
    },

    radioClick() {
      this.isOperateRadio = this.isOperateRadio ? "" : "1";
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/scss.scss";
.head-contain {
  @include flexLayout(center, space-between);
}
.file-btn {
  margin-bottom: 15px;
}
.address {
  display: inline-block;
  @include exceedFlow(1);
}
.el-input-number {
  width: 85%;
}
.left-width {
  width: 47%;
}
.imports {
  width: 6%;
  text-align: center;
  .import_btn {
    margin-top: 70px;
    margin-left: 0;
  }
  .el-icon-arrow-right {
    color: #5473e8;
    font-weight: bold;
  }
}
.list-title {
  text-align: center;

  .set_btn {
    margin-left: 10px;
  }
}
.operate-title {
  text-align: right;
  margin: 6px 0;
}
::v-deep .dialog-container .el-dialog__body {
  min-height: 240px;
}
::v-deep .operateDialog .el-dialog__body {
  min-height: 140px;
}
::v-deep .bind-operate {
  .el-radio__label {
    width: 75%;
  }
  .el-dialog__body {
    min-height: 140px;
  }
}
.tag-radio {
  margin-top: 14px;
}
.more {
  margin-left: 6px;
}
.add_tag_btn {
  margin-left: 10px;
}
.tagForm {
  margin-left: 120px;
  .el-icon-close {
    margin-left: 20px;
    font-size: 24px;
    position: relative;
    top: 4px;
    color: #999;
  }
}
.bind-title {
  margin: 0 0 30px;
}
.radio-one {
  @include flexLayout(center, flex-start);
  margin-left: 10%;
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>
